
//
//  HDStatusViewModel.swift
//  HDSwfitWeibo
//
//  Created by wty on 16/4/12.
//  Copyright © 2016年 wty. All rights reserved.
//

import UIKit
import SDWebImage

class HDStatusViewModel: NSObject {
    //创建请求状态
   var loadingStatus = false
    //创建一个单例
    static let  statusShare:HDStatusViewModel = HDStatusViewModel()
    
    
    //MARK -网络请求  回调模型数组出去
    func loadStatus(since_id: Int64, max_id: Int64,callBack:(statuses: [HDStatus]?,error:NSError?)->()){
        //如果已经存在一个请求 就不再操作 返回错误信息
        if loadingStatus {
            let error = HDNetworkErrorEnum.StatusLoading.error()
            callBack(statuses: nil, error: error)
            return
        }
        //发送网络请求  标记为正在加载微博  其他请求就加载不了  等网络请求完了再取消
        loadingStatus = true
        //从DAL来获取数据
        HDStatusDAL.shareDAL.loadStatus(since_id, max_id: max_id) { (status, error) -> () in
            self.loadingStatus = false
            //3.1字典转模型
            //1.创建可变数组
            var arrModel:[HDStatus] = []
            //2.遍历字典数组
            for  dict  in status!{
                let sta = HDStatus(dict: dict)
                arrModel.append(sta)
            }
            //3.缓存图片并且回调数据
            self.cacheWebImage(arrModel, callBack: callBack)
            
        }
    
    }
    
    //MARK - 缓存微博图片
    private func cacheWebImage( statuse : [HDStatus] ,callBack:(statuses: [HDStatus]?,error:NSError?)->()){
        //1.创建任务组
        let group = dispatch_group_create()
    
        //看看每个模型  是不是有图片下载    遍历模型 
        for  status in statuse {
            //原创的
            var  downloadURLs : [NSURL]?
            downloadURLs = status.storePictureURLs
            //转发的
            if downloadURLs == nil {
                downloadURLs = status.retweeted_status?.storePictureURLs
            }
            
            //看看是否有图片要下载
            if let urls = downloadURLs{
                if  urls.count == 1{
                    //获取一张图片的下载地址
                    let  url = urls.first!
                    //2.进入组
                    dispatch_group_enter(group)
                    //使用SDWebImage去异步下载图片  自动保存在沙盒cache中
                    SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (image, error, _, _, _) -> Void in
                        //3.离开调度组
                        dispatch_group_leave(group)
                        //如果下载失败
                        if error != nil {
                            HDPrint("下载图片失败")
                            return
                        }
                        //下载成功
                        HDPrint("下载成功")
                    })
                }
           
            }
            
            //4.监听所有微博图片下载  下载完成回调
            dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
                //下载完所需要图片后 才回调数据刷新界面
                callBack(statuses: statuse, error: nil)
            })
        
            
        }
    }
    
    //MARK -发微博
    func sendStatus(text:String ,image:UIImage?, sendStatusCallBack:(error:NSError?)->()){
        guard let access_token = HDUserAccoutViewModel.userAccoutShare.userAccount?.access_token else{
            let  error = HDNetworkErrorEnum.AccessTokenEmpty.error()
            sendStatusCallBack(error: error)
            return
        }
        //共用参数
        let  parameters = [
            "access_token":access_token,
            "status" : text
        ]
        if image == nil { //没有图片
            //url
            let  urlString = "https://api.weibo.com/2/statuses/update.json"
            
            //发送请求
            HDNetWorkTools.shareNetwork.POST(urlString, parameters: parameters, progress: nil, success: { (_, response) -> Void in
                sendStatusCallBack(error: nil)
                
                }) { (_, error) -> Void in
                    sendStatusCallBack(error: error)
            }
        }else{//有图片
            //url
              let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            //发送请求 将图片一起发
            HDNetWorkTools.shareNetwork.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formdata) -> Void in
                //将图片转换成二进制
                let  data = UIImagePNGRepresentation(image!)
                formdata.appendPartWithFileData(data!, name: "pic", fileName: "", mimeType: "image/png")
                }, progress: nil, success: { (_, _) -> Void in
                     sendStatusCallBack(error: nil)
                }, failure: { (_, error) -> Void in
                sendStatusCallBack(error: error)
            })
            
        }

        
        
        
    }
    

}
